package com.leetcode.offer.chapter4;


import java.util.ArrayList;
import java.util.List;

/**
 * @author Dennis Li
 * @date 2020/7/14 16:36
 */
public class TreeToDoublyList_36 {

    static class Node {
        public int val;
        public Node left;
        public Node right;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right) {
            val = _val;
            left = _left;
            right = _right;
        }
    }

    List<Node> list;

    public Node treeToDoublyList(Node root) {
        if (root == null) return null;
        list = new ArrayList<>();
        inorder(root);
        if (list.size() == 1) {
            Node res = list.get(0);
            res.left = res;
            res.right = res;
            return res;
        }
        // 对首尾结点进行处理
        list.get(0).left = list.get(list.size() - 1);
        list.get(0).right = list.get(1);

        list.get(list.size() - 1).left = list.get(list.size() - 2);
        list.get(list.size() - 1).right = list.get(0);

        for (int i = 1; i < list.size() - 1; i++) {
            list.get(i).left = list.get(i - 1);
            list.get(i).right = list.get(i + 1);
        }

        return list.get(0);
    }

    public void inorder(Node node) {
        if (node == null) return;
        inorder(node.left);
        list.add(node);
        inorder(node.right);
    }

    Node pre, head;

    public Node treeToDoublyList2(Node root) {
        if (root == null) return null;
        dfs(root);
        pre.right = head;
        head.left = pre;
        return head;
    }

    public void dfs(Node node) {
        /**
         * 由于采用的是中序遍历
         * 1. 会先往左子树遍历，左子树代表的是链表的头部，不断向左遍历相当于不断扩展链表的头部
         *      直到出栈的时候，遍历到最小结点，将其变为head结点
         * 2. 如果不是头部结点，那么其他是其前驱（左子树）的根节点，pre.right = node表示这是他的前驱
         */
        if (node == null) return;
        dfs(node.left);
        if (pre == null) head = node;
        // 由于在最后执行了pre的交替，所以后继是一直在更新的
        else pre.right = node;
        // 再执行结点自身的前驱更新
        node.left = pre;
        // 结点交替
        pre = node;
        dfs(node.right);
    }


}
